接續前一篇文章,今天要來講搭配點擊事件的運用
首先要先在Adapter新增recyclerview的點擊監聽
private OnItemClickListener listener;
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textView5 = itemView.findViewById(R.id.textView5);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null) {
String itemData = String.valueOf(dataList.get(position));
listener.onItemClick(itemData);
}
}
});
}
public interface OnItemClickListener {
void onItemClick(String selectedItem);
}
接著就能回到主程式去使用,延續上一篇使用的程式碼,我這邊把打開dialog寫在副程式裡,然後點擊事件也一起寫入
public void showDialog(){
dialog.show();
myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
@Override
public void onItemClick(String selectedItem) {
editText.setText(selectedItem);
dialog.dismiss();
}
});
}
之後回到button點擊監聽事件去呼叫副程式就可以囉
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
成果如下